﻿using Core.AdminUI.V2.Controllers.Base;
using Core.FrameWork.Commons.ApiResult;
using Core.FrameWork.Commons.Encrypt;
using Core.FrameWork.Models;
using Core.FrameWork.Models.Models.System;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System;
using System.Linq;
using System.Security.Claims;

namespace Core.AdminUI.V2.Controllers
{
    /// <summary>
    /// 账户安全控制器
    /// </summary>
    public class SSOController : BaseController
    {
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="adminContext"></param>
        public SSOController(AdminContext adminContext) : base(adminContext)
        {
        }
        /// <summary>
        /// 登录页面视图
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        public IActionResult Login()
        {
            return View();
        }
        /// <summary>
        /// 登出接口
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        public ActionResult Logout()
        {
            base.HttpContext.SignOutAsync().Wait();
            return this.Redirect("/SSO/Login");
        }
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="email"></param>
        /// <param name="newPassword"></param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost]
        public CommonResult SignLogin([FromForm] string admin, string password)
        {
            //验证 账号/密码 参数
            if (string.IsNullOrEmpty(admin))
            {
                return ApiRespHelp.getError(-100, "账号不能为空");
            }
            if (string.IsNullOrEmpty(password))
            {
                return ApiRespHelp.getError(-100, "密码不能为空");
            }

            var userInfo = _adminContext.SysAspNetUsers.AsNoTracking().FirstOrDefault(m => m.Phone == admin || m.Email == admin || m.Name == admin);

            //验证账号的 状态
            if (userInfo == null)
            {
                return ApiRespHelp.getError(-100, "用户不存在");
            }
            if (userInfo.IsDelete != 0)
            {
                return ApiRespHelp.getError(-100, "账户被禁止登录");
            }
            if (!userInfo.Password.Equals(MD5Util.GetMD5_16(password)))
            {
                return ApiRespHelp.getError(-100, "密码错误");
            }

            #region 写入Cookie
            //就很像一个CurrentUser,转成一个claimIdentity
            var claimIdentity = new ClaimsIdentity("Cookie");
            claimIdentity.AddClaim(new Claim(ClaimTypes.NameIdentifier, userInfo.Id.ToString()));
            claimIdentity.AddClaim(new Claim(ClaimTypes.Name, userInfo.Name));
            claimIdentity.AddClaim(new Claim(ClaimTypes.Email, userInfo.Email));
            var roleIds = _adminContext.SysAspNetUserRoles.Where(m => m.SysAspNetUsersId == userInfo.Id).Select(m => m.RoleId).ToList();
            if (roleIds.Count > 0)
            {
                var role = _adminContext.SysAspNetRoles.Where(m => roleIds.Contains(m.Id)).Select(m => m.Level).ToList();
                foreach (var item in role)
                {
                    claimIdentity.AddClaim(new Claim(ClaimTypes.Role, item.ToString()));
                }
            }
            var claimsPrincipal = new ClaimsPrincipal(claimIdentity);
            // 在上面注册AddAuthentication时，指定了默认的Scheme，在这里便可以不再指定Scheme。
            base.HttpContext.SignInAsync(claimsPrincipal, new AuthenticationProperties()
            {
                IsPersistent = true,
                ExpiresUtc = DateTime.Now.AddDays(1),
            }).Wait();//写到cookie
            #endregion

            return ApiRespHelp.getSuccess(Url.Content("~/Home/Index"));
        }
    }
}
